package org.farec.tcc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.farec.tcc.modelo.Email;

public class EmailDAO {
	
	private Connection connection;
	
	public EmailDAO(Connection connection)
	{
		this.connection = connection;
	}
	
	public Email getEmail(int codEmpresa)
	{
		try
		{
			Email email = new Email();
			
			PreparedStatement stmt = this.connection.prepareStatement("SELECT * from email where idempresa=?");
			stmt.setInt(1, codEmpresa);
			
			ResultSet rs = stmt.executeQuery();
			
			if(rs.next())
			{
				//Seta os valores
				email.setNome(rs.getString("nome"));
				email.setEmail(rs.getString("email"));
				email.setUsuario(rs.getString("usuario"));
				email.setSenha(rs.getString("senha"));
				email.setSmtp(rs.getString("smtp"));
				email.setPorta(Integer.parseInt(rs.getString("porta")));
			}
			
			rs.close();
			stmt.close();
			return email;
		}
		
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	public void adiciona(int codEmpresa, Email email)
	{
		// TODO Auto-generated method stub
		try
		{
			String  sql = "INSERT INTO email(nome,email,usuario,senha,smtp,porta,idempresa) VALUES(?,?,?,?,?,?,?)";
			PreparedStatement stmt = this.connection.prepareStatement(sql);
			
			stmt.setString(1, email.getNome());
			stmt.setString(2, email.getEmail());
			stmt.setString(3, email.getUsuario());
			stmt.setString(4, email.getSenha());
			stmt.setString(5, email.getSmtp());
			stmt.setInt(6, email.getPorta());
			stmt.setInt(7, codEmpresa);
			
			stmt.execute();
			stmt.close();
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	public void altera(int codEmpresa, Email email)
	{
		try
		{
			String sql = "UPDATE email SET nome=?, email=?, usuario=?, senha=?, smtp=?, porta=? WHERE idempresa=?";
			PreparedStatement stmt = this.connection.prepareStatement(sql);
			
			stmt.setString(1, email.getNome());
			stmt.setString(2, email.getEmail());
			stmt.setString(3, email.getUsuario());
			stmt.setString(4, email.getSenha());
			stmt.setString(5, email.getSmtp());
			stmt.setInt(6, email.getPorta());
			stmt.setInt(7, codEmpresa);
			
			stmt.execute();
			stmt.close();
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
	}

	public boolean existeContaEmail(int codEmpresa)
	{
		// TODO Auto-generated method stub
		try
		{
			String sql = "SELECT * from email WHERE idempresa=?";
			PreparedStatement stmt = this.connection.prepareStatement(sql);
			stmt.setInt(1, codEmpresa);
			
			ResultSet rs = stmt.executeQuery();
			
			if(rs.next())
			{
				return true;
			}
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
		
		return false;
	}
}
